package com.yunban.project.api.text_check.service;

import com.yunban.project.api.text_check.domain.CorrectionConfig;
import lombok.SneakyThrows;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: lijiajun
 * @date: 2024-11-20
 * @version: 1.0
 */
public interface CorrectionService {
    /**
     * 文本检查
     *
     * @param text 文本
     * @return Map
     */
    String correction(String text, CorrectionConfig config, String taskId);

//    public static void main(String[] args) {
//        String url = "https://mp.weixin.qq.com/s/KHi_yx1BSHNIBTwCBWpWWw";
//
//        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
//            // 创建GET请求
//            HttpGet request = new HttpGet(url);
//
//            // 设置User-Agent头部信息
//            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
//
//            // 执行请求并获取响应
//            HttpResponse response = httpClient.execute(request);
//
//            // 检查响应状态码
//            int statusCode = response.getStatusLine().getStatusCode();
//            if (statusCode == 200) {
//                // 获取响应体并转换为字符串
//                String htmlContent = EntityUtils.toString(response.getEntity(), "UTF-8");
//                System.out.println(htmlContent);
//            } else {
//                System.out.println("Failed to retrieve the page. Status code: " + statusCode);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    default String readLinkText(String link) {
        HttpGet request = new HttpGet(link);
        // 设置User-Agent头部信息
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
        // 执行请求并获取响应
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpResponse response = httpClient.execute(request);
            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应体并转换为字符串
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception ex) {
            throw new BusinessException("读取链接失败:" + ex.getMessage());
        }
        throw new BusinessException("读取链接失败");
    }

    @SneakyThrows
    default String readWord(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException("请上传你的word文件~");
        }
        // 获取inputStream
        InputStream inputStream = file.getInputStream();
        List<String> paragraphs = this.readWordContent(inputStream);
        return String.join("\n", paragraphs);
    }

    @SneakyThrows
    default List<String> readWordContent(InputStream inputStream) {
        byte[] fileData = inputStream.readAllBytes();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);

        // 检查文件是否为 .docx 格式
        if (isDocxFormat(fileData)) {
            return readDocxContent(byteArrayInputStream);
        } else {
            // 默认认为是 .doc 格式
            return readDocContent(byteArrayInputStream);
        }
    }

    private static boolean isDocxFormat(byte[] fileData) {
        // 检查文件前几个字节是否为 DOCX 文件的魔数
        // ZIP 文件的魔数，DOCX 是基于 ZIP 的
        byte[] docxMagicNumber = {0x50, 0x4B, 0x03, 0x04};
        if (fileData.length < docxMagicNumber.length) {
            return false;
        }
        for (int i = 0; i < docxMagicNumber.length; i++) {
            if (fileData[i] != docxMagicNumber[i]) {
                return false;
            }
        }
        return true;
    }

    private static List<String> readDocxContent(InputStream inputStream) throws IOException {
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            return document.getParagraphs().stream().map(XWPFParagraph::getText).collect(Collectors.toList());
        }
    }

    private static List<String> readDocContent(InputStream inputStream) throws IOException {
        try (HWPFDocument document = new HWPFDocument(inputStream)) {
            WordExtractor extractor = new WordExtractor(document);
            return List.of(extractor.getParagraphText());
        }
    }
}
